function ovec = orthvec(ivec, svec)
% orthvec  - cheap orthogonalization
%
% FORMAT:       ovec = orthvec(ivec, svec)
%
% Input fields:
%
%       ivec        vector to become orthogonal
%       svec        standard vector (unchanged)
%
% Output fields:
%
%       ovec        output vector

% Version:  v0.7f
% Build:    8110521
% Date:     Nov-05 2008, 9:00 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 2 || ...
   ~isa(ivec, 'double') || ...
   ~isa(svec, 'double') || ...
    ndims(ivec) ~= ndims(svec) || ...
    numel(ivec) ~= length(ivec) || ...
    any(size(ivec) ~= size(svec)) || ...
    any(isinf(ivec) | isnan(ivec) | isinf(svec) | isnan(svec))
    error( ...
        'BVQXtools:BadArgument', ...
        'Two same-dim vectors without Inf/Nans are required.' ...
    );
end

% calculate cov/corr
cv = sqrt(diag(cov([svec(:), ivec(:)])));
cr = corrcoef([svec(:), ivec(:)]);

% reshape ivec
ovec = ivec - (cr(2, 1) * cv(2) / cv(1)) * svec;

% clear dummy entries
ovec(abs(ovec) <= eps) = 0;
